package com.samphanie.auiu.router.test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZSY
 *
 * 买票的并发场景
 */
public class SynchronizedDemo {

    static List<String> tickets = new ArrayList<>();

    public static void buyTicket() {
        for (int i = 0; i < 100; i++) {
            tickets.add("票_" + (i + 1));
        }

        sellTikets();
    }

    private static void sellTikets() {

        final SynchronizedTestDemo synchronizedDemo = new SynchronizedTestDemo();

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronizedDemo.printThreadName();
                }
            }).start();
        }

    }

    static class SynchronizedTestDemo {
        synchronized void printThreadName() {
            String name = Thread.currentThread().getName();
            System.out.println("买票人：" + name + "准备好了...");
            synchronized (this) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("买票人：" + name + "正在卖票...");
            }

            System.out.println("买票人：" + name + "买到的票..." + tickets.remove(0));
        }
    }

}
